package com.zql.JianZhiOffer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created By ShuHua on 2022/5/3.
 */
public class Offer_21 {

    /**
     * 暴力解法
     * @param nums
     * @return
     */
    public int[] exchange(int[] nums) {
        List<Integer> js = new ArrayList<>();
        List<Integer> os = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if((nums[i]%2==0)?(os.add(nums[i])):(js.add(nums[i]))){
            }
        }
        for (int i = 0; i < js.size(); i++) {
            nums[i]=js.get(i);
        }
        for (int i = js.size(); i < js.size()+os.size(); i++) {
            nums[i]=os.get(i-js.size());
        }
        return nums;
    }

    /**
     * 双指针法
     * @param nums
     * @return
     */
    public int[] exchange2(int[] nums) {
        int i=0;
        int j=nums.length-1;
        while (i<j){
            //如果是奇数 i++,直到找到偶数
            while (nums[i]%2!=0&&i<j)i++;
            //如果数偶数 j--,直到找到奇数
            while (nums[j]%2==0&&j>i)j--;
            int tmp =nums[i];
            nums[i]=nums[j];
            nums[j]=tmp;
        }
        return nums;
    }
}
